#!/usr/bin/with-contenv bashio

# 导入工具函数
source /utils.sh
source /resource_manager.sh
source /gitee_api.sh

# 配置变量
GITEE_REPO=$(bashio::config 'gitee_repo')
WWW_DIR="/homeassistant/www"
COMMUNITY_DIR="${WWW_DIR}/community"
STORAGE_DIR="/homeassistant/.storage"
RESOURCES_FILE="${STORAGE_DIR}/lovelace_resources"

# 验证 Gitee 仓库地址
if ! validate_gitee_url "${GITEE_REPO}"; then
    bashio::log.error "无效的 Gitee 仓库地址: ${GITEE_REPO}"
    exit 1
fi

# 创建必要的目录
mkdir -p "${WWW_DIR}" "${COMMUNITY_DIR}" "${STORAGE_DIR}"
if [ $? -ne 0 ]; then
    bashio::log.error "创建必要目录失败"
    exit 1
fi

# 初始化资源文件
if [ ! -f "${RESOURCES_FILE}" ]; then
    echo '{"version":1,"minor_version":1,"key":"lovelace_resources","data":{"items":[]}}' > "${RESOURCES_FILE}"
    if [ $? -ne 0 ]; then
        bashio::log.error "初始化资源文件失败"
        exit 1
    fi
fi

# 获取仓库文件列表
FILES=$(get_repo_files "${GITEE_REPO}")
if [ $? -ne 0 ] || [ -z "${FILES}" ]; then
    bashio::log.error "获取仓库文件列表失败"
    exit 1
fi

bashio::log.info "找到以下 JS 文件："
echo "${FILES}" | while read -r file; do
    bashio::log.info "- ${file}"
done

# 获取现有资源列表
EXISTING_URLS=$(jq -r '.data.items[].url' "${RESOURCES_FILE}")

# 下载并处理文件
echo "${FILES}" | while read -r FILE; do
    REPO_PATH=$(echo "${GITEE_REPO}" | sed -n 's|https://gitee.com/\([^/]*/[^/]*\).*|\1|p')
    FILE_URL="https://gitee.com/${REPO_PATH}/raw/master/${FILE}"
    LOCAL_PATH="${COMMUNITY_DIR}/${FILE}"
    RESOURCE_URL="/local/community/${FILE}"
    
    # 检查是否已存在
    if echo "${EXISTING_URLS}" | grep -q "^${RESOURCE_URL}$"; then
        bashio::log.info "${FILE} 资源已存在,跳过..."
        continue
    fi
    
    bashio::log.info "正在下载 ${FILE}..."
    
    # 下载文件
    if curl -s -L -o "${LOCAL_PATH}" "${FILE_URL}"; then
        bashio::log.info "下载成功: ${FILE}"
        
        # 添加到资源配置
        if ! add_resource "${RESOURCES_FILE}" "${RESOURCE_URL}"; then
            bashio::log.warning "资源 ${FILE} 添加失败，继续处理其他文件..."
            continue
        fi
    else
        bashio::log.error "下载失败: ${FILE_URL}"
    fi
done

bashio::log.info "处理完成"

# 保持容器运行
while true; do
    sleep 3600
done